/**
 * message.js file;
 * company:junqitecch
 * author:xuzuiotao
 * message module,uses local https port http://127.0.0.1:8025/ios|android|web/sms/send
 * for GeTui and SMS
 */

var  consts  = require('../consts');
var users= require('../db/users');

var rongcloudSDK = require( 'rongcloud-sdk' );
rongcloudSDK.init( consts.RongCloud.APP_KEY, consts.RongCloud.APP_SECRET);

function getIMToken(entity,callback){
	if(typeof(entity.imToken)!=='undefined' && entity.imToken !==null){
		
		rongcloudSDK.user.refresh(entity.userID+'', entity.nickName+'', entity.iconURL+'', function( err, resultText ) {
		    	  
			console.log('rongcloud refresh');
			if( err ) {
			    
			}else {
			    var result = JSON.parse( resultText );
			    if( result.code == 200 ) {
			    	
			    	if(typeof(result.token)!=='undefined'&&result.token!==null){
			    		entity.imToken = result.token;
						console.log('aaaaa' + result.token);

				    	var value=[];
	    			    value.im_token=result.token;
	    			    users.update(entity.userID,value);
			    		
			    	}
			    	
			    }
			}
			if(callback){
				callback(null);
			}
			
		});
		
	}else{
			
		console.log('rongcloud create');

		rongcloudSDK.user.getToken(entity.userID+'', entity.nickName+'', entity.iconURL+'', function( err, resultText ) {
		    	  
			if( err ) {
			
			}else {
			    var result = JSON.parse( resultText );
			    if( result.code == 200 ) {
			    	entity.imToken = result.token;
			    	var values= [];
    			    values.im_token=result.token;
    			    console.log('aamma  '+values.im_token);
    			    users.update(entity.userID,values,null);
			    }
			}
			console.log('33333'+entity.imToken);

			if(callback){
				callback(null);
			}
			
		});
		
	}
	
}

module.exports = {
	getIMToken: getIMToken,

};
